<template>
  <template v-for="item in fileMenu" :key="item.id">
    <el-sub-menu :index="item.id" v-if="item.children && item.visible">
      <template #title>
        <el-icon><Folder></Folder></el-icon>
        <span>{{ formatName(item.name)[0] }}</span>
        <span class="hight_light">{{ formatName(item.name)[1] }}</span>
        <span>{{ formatName(item.name)[2] }}</span>
      </template>
      <SubMenu
        :fileMenu="item.children"
        @selectHandleItem="selectHandleItem"
      ></SubMenu>
    </el-sub-menu>
    <el-menu-item
      :index="item.id"
      @click="handleClick(item)"
      v-else-if="!item.children && item.visible"
    >
      <el-icon><Document></Document></el-icon>
      <span>{{ formatName(item.name)[0] }}</span>
      <span class="hight_light">{{ formatName(item.name)[1] }}</span>
      <span>{{ formatName(item.name)[2] }}</span>
    </el-menu-item>
  </template>
</template>

<script lang="ts" setup>
import { Folder, Document } from '@element-plus/icons-vue'
import type { PropType } from 'vue'
import SubMenu from './SubMenu.vue'
import type { FileMenu } from './types'
import { useFloderMenuStore } from '@/stores/index'

defineProps({
  fileMenu: {
    type: Array as PropType<FileMenu>,
    default: () => []
  }
})

const floderMenuStore = useFloderMenuStore()

function formatName(name: string) {
  let newName: string
  const regexp = new RegExp(floderMenuStore.searchKeyword, 'ig')
  if (floderMenuStore.searchKeyword && regexp.test(name)) {
    newName = name.replace(regexp, ($0) => {
      return `|${$0}|`
    })
  } else {
    newName = name + '||'
  }

  const arr = newName.split('|')
  return arr
}
const emit = defineEmits(['selectHandleItem'])
const handleClick = (item: any) => {
  emit('selectHandleItem', item)
}
const selectHandleItem = (item: any) => {
  emit('selectHandleItem', item)
}
</script>

<style scoped lang="less">
.hight_light {
  color: rgb(221, 40, 161);
  font-weight: bold;
}
</style>
